﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace EMIS.Http
{
    public static class HttpHelper
    {
        /// <summary>
        /// 测试api连接
        /// </summary>
        public const string HttpTestApi = "api/common/test";

        /// <summary>
        /// 获取人员信息
        /// </summary>
        public const string InsertWarning = "api/warning/insertInfo";
        /// <summary>
        /// 获取环境参数
        /// </summary>
        public const string GetEnvironmentData = "api/values/getdata";

        /// <summary>
        /// 连接网络
        /// </summary>
        /// <param name="apiUrl">请求url</param>
        /// <param name="serverAddress">网络连接地址</param>
        /// <param name="parameters">请求参数</param>
        /// <param name="timeOut">连接超时时间</param>
        /// <returns>请求结果</returns>
        public static ResponseResult Get(string serverAddress, string apiUrl, Dictionary<string, string> parameters = null, int timeOut = 5 * 1000)
        {
            ResponseResult result = new ResponseResult();

            // 拼接参数
            string url = serverAddress + apiUrl;
            if (parameters != null && parameters.Count > 0)
            {
                url = $"{url}?";
                foreach (KeyValuePair<string, string> pair in parameters)
                {
                    url += $"&{pair.Key}={pair.Value}";
                }
            }

            // 发送请求
            WebRequest request = WebRequest.Create(url);
            request.Timeout = timeOut;
            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                // 判断是否连接成功
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    Stream dataStream = response.GetResponseStream();
                    if (dataStream == null)
                    {
                        return result;
                    }
                    StreamReader reader = new StreamReader(dataStream);
                    result = JsonConvert.DeserializeObject<ResponseResult>(reader.ReadToEnd());
                    reader.Close();
                    response.Close();
                }
            }
            catch (Exception e)
            {
                result.Code = ResponseCode.Error;
            }
            return result;
        }

        /// <summary>
        /// POST请求
        /// </summary>
        /// <param name="serverAddress">服务器地址</param>
        /// <param name="apiUrl">api接口</param>
        /// <param name="parameters">参数</param>
        /// <param name="timeOut">超时时间</param>
        /// <returns></returns>
        public static ResponseResult Post(string serverAddress, string apiUrl, string parameters = "", int timeOut = 5 * 1000)
        {
            ResponseResult result = new ResponseResult();
            string url = serverAddress + apiUrl;
            WebRequest request = WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/json;charset=utf-8";
            if (!string.IsNullOrWhiteSpace(parameters))
            {
                var bytes = Encoding.UTF8.GetBytes(parameters);
                int len = bytes.Length;
                request.ContentLength = len;
                var requestStream = request.GetRequestStream();
                requestStream.Write(bytes,0, len);
                requestStream.Flush();
                requestStream.Close();
            }

            var webResponse = request.GetResponse();
            var responseStream = webResponse.GetResponseStream();
            if (responseStream != null)
            {
                StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                var responseStr = reader.ReadToEnd();
                responseStream.Close();
                reader.Close();
                result = JsonConvert.DeserializeObject<ResponseResult>(responseStr);
            }
            return result;
        }
    }
}
